/*
 * @Author: xiaosihan 
 * @Date: 2023-04-10 16:26:59 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-23 12:51:52
 */



const fs = require("fs");
const tinify = require("tinify");
const path = require("path");

const keys = [
    // { key: "I7hDO2OgJ89OMBLrEqjCCiGZFrHsy1Fh", conut: 0 },
    { key: "g5rrMCW88c4ZmWwBtYR4vryGHFkW1TPr", conut: 0 },
];

// tinify.key = "I7hDO2OgJ89OMBLrEqjCCiGZFrHsy1Fh";

// 代理地址
// tinify.proxy = "http://user:pass@192.168.0.1:8080";

const filenames = fs.readdirSync("./").filter(filename => /\.(jpg|jpeg|png)/.test(filename));

(async () => {
    console.log(`共${filenames.length}张图片`);
    const startTime = new Date().valueOf();
    const task = [];
    for (let i in filenames) {
        const filename = filenames[i];

        if (/\.(jpg|jpeg|png)$/.test(filename)) {
            task.push(new Promise(async (resolve, reject) => {
                let file_path = path.resolve(filename);
                console.log(`${filename}`);
                const key = keys[i % keys.length].key;
                tinify.key = key;
                try {
                    await tinify.fromFile(file_path).toFile(file_path)
                } catch (error) {
                    console.log('error', error);
                }

                keys.map(k => {
                    if (k.key === key) {
                        k.conut = Math.max(k.conut, tinify.compressionCount);
                    }
                });
                resolve();
            }));
        }

    }

    await Promise.all(task);
    const endTime = new Date().valueOf();
    const time = ((endTime - startTime) / 1000).toFixed(1);
    keys.map(k => {
        console.log(k.key, `已用${k.conut}`);
    });
    console.log('总耗时', time, "秒");
})();